import React, { useEffect, useState, useRef } from 'react'
import './SwiperImg.scss'
import axios from 'axios'
import { BarChartOutlined, CopyOutlined, CrownOutlined, DeleteOutlined, EditOutlined, EllipsisOutlined, EyeOutlined, FileDoneOutlined, FolderOutlined, RocketOutlined } from '@ant-design/icons';

import { getWorksImg } from '../../api/swiperImg.js'
const processImageUrl = (url: string) => {
  if (url.startsWith('http')) return url;

  const match = url.match(/url\(['"]?(.*?)['"]?\)/);
  if (match && match[1]) {
    return match[1]
      .replace(/&quot;?/g, '')
      .replace(/\\/g, '')
      .replace(/\|/g, '%7C');
  }

  return url
    .replace(/&quot;?/g, '')
    .replace(/\\/g, '')
    .replace(/\|/g, '%7C');
};

function SwiperImg() {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentIndex, setCurrentIndex] = useState(0)
  const [showArrows, setShowArrows] = useState(false) // 新增状态用于控制箭头显示
  const swiperRef = useRef<HTMLDivElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }
  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true)
      const res = await getWorksImg({
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      })

      const fixedData = res.data.map((item: any) => ({
        ...item,
        img: processImageUrl(item.img)
      }))

      setPicture(fixedData)
      setError(null)
    } catch (err: any) {
      console.error('图片加载失败:', err)
      setError('图片加载失败，请查看控制台')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  const ITEM_WIDTH = 240;
  const GAP = 15;
  const ITEM_TOTAL_WIDTH = ITEM_WIDTH + GAP;
  // 在useEffect中添加重计算逻辑
  useEffect(() => {
    if (!loading && !error) {
      // 使用 requestAnimationFrame 确保 DOM 已更新
      requestAnimationFrame(() => {
        calculateArrows();
        // 初始时重置索引
        setCurrentIndex(0);
      });
    }
  }, [loading, error, picture]);

  // 新增：计算是否应该显示箭头
  const calculateArrows = () => {
    if (!swiperRef.current || !wrapperRef.current) {
      setShowArrows(false);
      return;
    }

    const containerWidth = swiperRef.current.offsetWidth;
    const contentWidth = wrapperRef.current.scrollWidth;

    // 只有当内容宽度大于容器宽度时才显示箭头
    setShowArrows(contentWidth > containerWidth);
  };

  // 修改：添加窗口大小变化的监听
  useEffect(() => {
    const handleResize = () => calculateArrows();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);



  // 计算是否显示箭头
  const showLeftArrow = showArrows && currentIndex > 0;
  const showRightArrow = showArrows && (() => {
    if (!swiperRef.current || !wrapperRef.current) return false;

    const containerWidth = swiperRef.current.offsetWidth;
    const contentWidth = wrapperRef.current.scrollWidth;
    const maxScroll = contentWidth - containerWidth;

    // 添加容错处理，确保不会出现负值
    return currentIndex * ITEM_TOTAL_WIDTH < Math.max(0, maxScroll);
  })();

  const handlePrev = () => {
    if (currentIndex > 0) {
      setCurrentIndex(prev => prev - 1);
    }
  };

  const handleNext = () => {
    if (showRightArrow) {
      setCurrentIndex(prev => prev + 1);
    }
  };

  // 计算包裹器的偏移量
  const wrapperStyle = {
    transform: `translateX(-${currentIndex * ITEM_TOTAL_WIDTH}px)`
  };

  return (
    <div className='swiper-box' ref={swiperRef}>
      {/* 左箭头 - 只在需要时显示 */}
      <div
        className={`swiper-arrow left ${showLeftArrow ? '' : 'hidden'}`}
        onClick={handlePrev}
      >
        &lt;
      </div>

      {/* 右箭头 - 只在需要时显示 */}
      <div
        className={`swiper-arrow right ${showRightArrow ? '' : 'hidden'}`}
        onClick={handleNext}
      >
        &gt;
      </div>

      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"
        ref={wrapperRef}
        style={wrapperStyle}
      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
              >
                <EllipsisOutlined />
                <div className={`hover-content ${showMenu ? 'visible' : ''}`} onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>

              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form'>表单</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>
              </div>

              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export default SwiperImg


export const SwiperImg2 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }

  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/24', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' style={{ color: "#548dff", background: '#e7efff' }}>H5</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>

              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export const SwiperImg3 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }

  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/23', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' style={{ color: "#7060ed", background: '#f0effd' }}>海报</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>

              <div className="hover-icons">
                <div className="icon-item">
                  <EditOutlined />
                  <span>编辑</span>
                </div>
                <div className="icon-item">
                  <BarChartOutlined />
                  <span>数据</span>
                </div>
                <div className="icon-item">
                  <RocketOutlined />
                  <span>推广</span>
                </div>

                <div className='swiper-memories'>

                  <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                  <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                  <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
                </div>
              </div>


            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export const SwiperImg4 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }

  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/20', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' style={{ color: "#f3753d", background: '#fef1ec' }}>长页</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>

              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export const SwiperImg5 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }

  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/19', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' >表单</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>
              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export const SwiperImg6 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }


  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/22', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])




  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' style={{ color: "#f4ab2e", background: '#fef6eb' }}>互动</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>

              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}

export const SwiperImg7 = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showMenu, setShowMenu] = useState(false)
  const [menuTimeout, setMenuTimeout] = useState(null)

  const handleMouseEnter = () => {
    if (menuTimeout) clearTimeout(menuTimeout)
    setShowMenu(true)
  }
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      setShowMenu(false)
    }, 500)
    setMenuTimeout(timeout)
  }

  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true);
      // 调用分组接口获取多张图片
      const res = await axios.get('http://localhost:3000/api/images/21', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      });

      // 确保处理的是数组
      const fixedData = Array.isArray(res.data)
        ? res.data.map((item: any) => ({
          ...item,
          img: processImageUrl(item.img)
        }))
        : [{
          ...res.data,
          img: processImageUrl(res.data.img)
        }];

      setPicture(fixedData);
      setError(null);
    } catch (err: any) {
      // 错误处理保持不变
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getImg()
  }, [])



  return (
    <div className='swiper-box' >


      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"

      >
        {!loading && !error && picture.map(item => (
          <div className="swiper-item" key={item.id}>
            <div className="swiper-img">
              {/* 添加蒙层和操作图标 */}
              <div className="image-hover-layer"></div>
              <div className="dot-menu"
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}>
                <EllipsisOutlined />
                <div
                  className={`hover-content ${showMenu ? 'visible' : ''}`}
                  onMouseEnter={handleMouseEnter}
                  onMouseLeave={handleMouseLeave}>
                  <div><CopyOutlined style={{ margin: '0px 6px' }} />复制</div>
                  <div><FolderOutlined style={{ margin: '0px 6px' }} />移动至...</div>
                  <div style={{ borderBottom: '1px solid #ccc' }}><FileDoneOutlined style={{ margin: '0px 6px' }} />提交审批<CrownOutlined style={{ margin: '0px 6px', color: 'gold' }} /></div>
                  <div><DeleteOutlined style={{ margin: '0px 6px' }} />删除</div>
                </div>
              </div>
              <div className="preview-icon">
                预览
              </div>
              <div className="no-publish">未发布</div>
              <img
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text">
              <div className="default-content">
                <span className='swiper-form' style={{ color: "#43a471", background: '#ecf5f0' }}>视频</span>
                <h5 style={{ fontSize: '14px', marginTop: '15px' }}>画出你心目中最美的TA投票...</h5>
                <time style={{ color: "#ababab" }}>2025-05-30</time>

              </div>

              <div className="hover-icons">
                <div className="hover-icons-box">
                  <div className="icon-item">
                    <EditOutlined />
                    <span>编辑</span>
                  </div>
                  <div className="icon-item">
                    <BarChartOutlined />
                    <span>数据</span>
                  </div>
                  <div className="icon-item">
                    <RocketOutlined />
                    <span>推广</span>
                  </div>
                </div>



              </div>

              <div className='swiper-memories'>
                <p><span style={{ color: '#1d68ff' }}>0</span> 浏览</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 访客</p>
                <p><span style={{ color: '#1d68ff' }}>0</span> 表单</p>
              </div>
            </div>



          </div>
        ))}
      </div>
    </div>
  )
}




export const SelectedTemplatesImg = () => {
  const [picture, setPicture] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentIndex, setCurrentIndex] = useState(0)
  const [showArrows, setShowArrows] = useState(false) // 新增状态用于控制箭头显示
  const swiperRef = useRef<HTMLDivElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)
  //获取图片数据
  const getImg = async () => {
    try {
      setLoading(true)
      const res = await axios.get('http://localhost:3000/api/images?group=img3', {
        headers: {
          'Referrer-Policy': 'no-referrer-when-downgrade',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
      })

      const fixedData = res.data.map((item: any) => ({
        ...item,
        img: processImageUrl(item.img)
      }))

      setPicture(fixedData)
      setError(null)
    } catch (err: any) {
      console.error('图片加载失败:', err)
      setError('图片加载失败，请查看控制台')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    getImg()
  }, [])

  const ITEM_WIDTH = 240;
  const GAP = 15;
  const ITEM_TOTAL_WIDTH = ITEM_WIDTH + GAP;
  // 在useEffect中添加重计算逻辑
  useEffect(() => {
    if (!loading && !error) {
      // 使用 requestAnimationFrame 确保 DOM 已更新
      requestAnimationFrame(() => {
        calculateArrows();
        // 初始时重置索引
        setCurrentIndex(0);
      });
    }
  }, [loading, error, picture]);

  // 新增：计算是否应该显示箭头
  const calculateArrows = () => {
    if (!swiperRef.current || !wrapperRef.current) {
      setShowArrows(false);
      return;
    }

    const containerWidth = swiperRef.current.offsetWidth;
    const contentWidth = wrapperRef.current.scrollWidth;

    // 只有当内容宽度大于容器宽度时才显示箭头
    setShowArrows(contentWidth > containerWidth);
  };

  // 修改：添加窗口大小变化的监听
  useEffect(() => {
    const handleResize = () => calculateArrows();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);



  // 计算是否显示箭头
  const showLeftArrow = showArrows && currentIndex > 0;
  const showRightArrow = showArrows && (() => {
    if (!swiperRef.current || !wrapperRef.current) return false;

    const containerWidth = swiperRef.current.offsetWidth;
    const contentWidth = wrapperRef.current.scrollWidth;
    const maxScroll = contentWidth - containerWidth;

    // 添加容错处理，确保不会出现负值
    return currentIndex * ITEM_TOTAL_WIDTH < Math.max(0, maxScroll);
  })();

  const handlePrev = () => {
    if (currentIndex > 0) {
      setCurrentIndex(prev => prev - 1);
    }
  };

  const handleNext = () => {
    if (showRightArrow) {
      setCurrentIndex(prev => prev + 1);
    }
  };

  // 计算包裹器的偏移量
  const wrapperStyle = {
    transform: `translateX(-${currentIndex * ITEM_TOTAL_WIDTH}px)`
  };

  return (
    <div className='swiper-box' ref={swiperRef}>
      {/* 左箭头 - 只在需要时显示 */}
      <div
        className={`swiper-arrow left ${showLeftArrow ? '' : 'hidden'}`}
        onClick={handlePrev}
      >
        &lt;
      </div>

      {/* 右箭头 - 只在需要时显示 */}
      <div
        className={`swiper-arrow right ${showRightArrow ? '' : 'hidden'}`}
        onClick={handleNext}
      >
        &gt;
      </div>

      {loading && <div className="loading">图片加载中...</div>}
      {error && <div className="error">{error}</div>}

      <div
        className="swiper-wrapper"
        ref={wrapperRef}
        style={wrapperStyle}
      >
        {!loading && !error && picture.map(item => (
          <div className="seleted-item" key={item.id} style={{ width: '200px', height: '340px' }}>
            <div className="swiper-img" style={{ width: '100%', height: '85%' }}>

              <div className="h5">H5</div>
              <img
                style={{ borderRadius: "8px" }}
                src={item.img}
                alt="表单图片"
                referrerPolicy="no-referrer"
                onError={(e) => {
                  console.error('图片加载失败:', item.img);
                  const target = e.target as HTMLImageElement;
                  target.style.backgroundColor = '#eee';
                  target.alt = '图片加载失败';
                }}
              />
            </div>
            <div className="swiper-text" style={{ width: '100%', height: '15%' }}>
              <div >

                <h6 style={{ fontSize: '12px' }}>画出你心目中最美的TA投票...</h6>


              </div>

              <div className="hover-text" style={{ fontSize: '12px' }}>

                <div className="hover-img">
                  <img
                    src="https://ts1.tc.mm.bing.net/th/id/OIP-C.Ko3rLErQKPke4WpPgvdBBAHaHa?w=210&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.6&pid=3.1&rm=2"
                    alt="" style={{ width: '20px', height: '20px', borderRadius: '50%' }} />
                  <span>梦想者</span>
                </div>

                <div className="hover-img">

                  <span><EyeOutlined />  1041</span>
                </div>

              </div>


            </div>



          </div>
        ))}
      </div>
    </div>
  )
}
